<?php
namespace app\api\model;
use think\Cache;
use controller\Easemob;

class User extends Common
{
    /**
     * 用户注册
     */
    public function register($data)
    {
        $name = $data['name'];
        $mobile  = $data['mobile'];

        $user = $this->where('mobile',$mobile)->where('state','<>','2')->find();
        if($user) {return 500;}; 
        $user = $this->where('name',$name)->where('state','<>','2')->find();
        if($user) {return 501;}; 
        $h = new Easemob();
        $hx_username = strtolower(GetfourStr(4)."_".substr($mobile,-4));
        $hx_password = substr($mobile,-6);
        $hx_user = $h->getUser($hx_username);
        $h->createUser($hx_username,$hx_password);
        $data['hx_username'] = $hx_username;
        $data['hx_password'] = $hx_password;
        $data['state'] = $data['role'] == 2 ? 1:0;

        if($data['role'] == 1)
        {
            $options = array(
                'groupname'=>$name,
                'desc'=>$name.'群信息',
                'owner'=>$hx_username,
                'public'=>true,
                'approval'=>false,
            );
            $data['hx_groupid']  = $h->createGroup($options);
        }
        
        if($this->data($data)->allowField(true)->save() !== false)
        {
            if($data['role'] == 1)
            {
                //$qrcode = qrcode($this->id,url('Community/checkin',['communityid'=>$this->id])); 
                $qrcode = qrcode($this->id,url('Index/login',['communityid'=>$this->id])); 
                $this->where(['id'=>$this->id])->update(['qrcode'=>$qrcode]);
            }
            else
            {
                $data['user_id'] = $this->id;
                $data['state'] = 0;
                model('CommunityMember')->allowField(true)->save($data);
                $community = $this->get($data['community_id']);
                $this->addGroupMember($community['hx_groupid'],$this->hx_username);
            }
            return 0;
        }

        return 503;
    }

    /**
     * 用户登录认证
     */
    public function login($mobile, $password){
        $map['mobile'] = $mobile;
        /* 获取用户数据 */
        $user = $this->where($map)->find();
        $userAuth = model('RealAuth')->get(['type'=>2,'user_id'=>$user['id'],'state'=>1]);

        if($user){
            //:0=审核中,1=审核通过,2=审核未通过
            if($user['state'] == 0)
            {
                return -5;
            }
            else if($user['state'] == 2)
            {
                return -6;
            }
            /* 验证用户密码 */
            if($password==Cache::get($mobile))
            {
                // 生成 token
                $token = buildToken($user->name);
                Cache::set(config('tokenPrefix') . $token, $user->id, config('token_expires'));
                $is_realauth = $is_bank = $is_transpwd = 0;
                if($userAuth)
                {
                    $is_realauth = 1;
                    if($userAuth['card_no'])$is_bank = 1;
                    if($userAuth['transpwd'])$is_transpwd = 1;
                }
                $data = [
                    'token' => $token,
                    'id'    => $user['id'],
                    'role'  => $user['role'],
                    'state' => $user['state'],
                    'mobile'      => $user['mobile'],
                    'name'        => $user['name'],
                    'avatar'      => $user['avatar'],
                    'is_realauth' => $is_realauth,
                    'is_bank' => $is_bank,
                    'is_transpwd' => $is_transpwd,
                    'hx_username' => $user['hx_username'],
                    'hx_password' => $user['hx_password'],
                ];
                if($user['role'] == 1)
                {
                    $data['hx_groupid'] = $user['hx_groupid'];
                    $data['person']     = $user['person'];
                    $data['is_pay']     = $user['is_pay'];
                }
                return $data; //登录成功，返回用户ID
            } 
            else 
            {
                return 0; //密码错误
            }
        }
        else 
        {
            return 0; //用户不存在或被禁用
        }
    }

    public function logout()
    {
        cache(config('tokenPrefix').$this->token, NULL);
        cache(config('tokenAndUserPrefix') . $user['id'], NULL);
    }

    public function getUserInfo($token)
    {
        $user_id = Cache::get(config('tokenPrefix') . $token);

        if ($user_id == false) return false;

        $user = $this->where('id',$user_id)->find();
        
        return $user;
    }

    public function addFriend($username,$friend_name)
    {
        $h = new Easemob();
        $result = $h->addFriend($username,$friend_name);
        if($result)
        {
             return true;
        }
        return false;
    }

    public function showFriends($username)
    {
        $h = new Easemob();
        $hx_friends = $h->showFriends($username);
        $result = [];
        foreach ($hx_friends['data'] as $k => $v) {
           $friend = $this->get(['hx_username'=>$v]);
           $result[] = [
                'user_id'  => $friend['id'],
                'username' => $friend['name'],
                'avatar'   => $friend['avatar'],
           ]; 
        }
        return $result;
    }

    public function createGroup($username)
    {
        $h = new Easemob();
        $options = array(
            'groupname'=>'未命名',
            'desc'=>'',
            'owner'=>$username,
            'public'=>true,
            'approval'=>false,
        );
        return  $h->createGroup($options);
    }

    public function deleteGroupMember($groupid,$username)
    {
        $h = new Easemob();
        return $h->deleteGroupMember($groupid,$username);
    }

    public function addGroupMember($groupid,$username)
    {
        $h = new Easemob();
        return $h->addGroupMember($groupid,$username);
    }

    public function Community()
    {
        return $this->belongsToMany('Community','\app\api\model\CommunityMember');
    }

  /*  public function static getHeldsdatas($string)
    {
        $valueArr = explode(',', $string);
        $list = $this->getHeldsdataList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }
*/
}